package com.zryc.shop.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zryc.shop.pms.entity.Brand;
import com.zryc.shop.pms.mapper.BrandMapper;
import com.zryc.shop.pms.service.IBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 品牌表 服务实现类
 * </p>
 *
 * @author LiYe
 * @since 2023-02-09
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public IPage<Brand> page(String keyword, Integer pageNum, Integer pageSize) {
        Page page = new Page(pageNum, pageSize);
        if (pageSize < 100) {//如果分页小于100条每页，从MySQL数据库中进行分页查询即可，不走缓存
            QueryWrapper queryWrapper = new QueryWrapper();
            if (!StringUtils.isEmpty(keyword)) {
                queryWrapper.like("name", keyword);
            }
            this.page(page, queryWrapper);
        } else {//如果分页大于等于100条每页，商品管理中查询全部品牌，就需要对数据进行缓存
            final String brandListKey = "BRAND_LIST_KEY";
            if (redisTemplate.hasKey(brandListKey)) {//判断redis数据库中是否存在这个key
                // brandList从Redis缓存中获取
                System.out.println("----------------------------在Redis DB中查询到品牌列表------------------------------");
                List brandList = redisTemplate.opsForList().range(brandListKey, 0, -1);
                page.setRecords(brandList);
            } else {//1.品牌列表还未保存到redis缓存中 2.该key已经过期
                System.out.println("----------------------------Redis缓存已过期，重新查询MySQL数据库------------------------------");
                page = this.page(page);//查询MySQL数据库，得到品牌列表
                redisTemplate.opsForList().rightPushAll(brandListKey, page.getRecords());//更新Redis缓存
                redisTemplate.expire(brandListKey, 10, TimeUnit.MINUTES);//这个缓存的有效时间为10分钟
            }
        }
        return page;
    }
}
